package com.mxy.myapplication2.java;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.mxy.myapplication2.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 自定义下拉刷新效果，内嵌非列表控件
 *
 * @author 马晓勇
 */
public class CustomizedRefreshNoneListFragment extends Fragment {

    private InterceptNestedScrollView nsv;

    /**
     * 头部下拉视图，高度固定
     */
    private View topViewInNsv;

    /**
     * 伸缩视图，在topViewInNsv内部，跟随用户拖动幅度实时变更高度
     */
    private View flexibleLayout;
    private ObjectAnimator objectAnimator;
    private boolean isRefresh = false;
    private View textView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w("MXY", "onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.w("MXY", "onCreateView");
        return inflater.inflate(R.layout.item_customizedrefreshexample_viewpager_nonelist, container, false);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.w("MXY", "onViewCreated");
        noneListViewInit(view);
    }

    /**
     * 内嵌非列表控件刷新效果view
     */
    private void noneListViewInit(View v) {
        nsv = v.findViewById(R.id.nsv);
        nsv.setSmoothScrollingEnabled(true);
        nsv.setOnTouchListener(new NsvTouchListener());
        nsv.setOnScrollChangeListener(new NsvScrollChangeListener());
        topViewInNsv = v.findViewById(R.id.topViewInNsv);
        flexibleLayout = v.findViewById(R.id.flexibleLayout);
        textView = v.findViewById(R.id.textView);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // requestLayout()会触发onMeasure()和layout()
                textView.requestLayout();
                // Invalidate()会触发onDraw()
                textView.postInvalidate();
            }
        });

        textView.getViewTreeObserver().addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
            @Override
            public void onWindowFocusChanged(boolean hasFocus) {
                Log.w("MXY", "CusTextView onWindowFocusChanged hasFocus = " + hasFocus);
            }
        });

        //注意先初始化footballIv
        View footballIv = v.findViewById(R.id.footballIv);
        objectAnimator = ObjectAnimator.ofFloat(footballIv, "rotation", 0f, 1440f);
        objectAnimator.setDuration(2000);
        objectAnimator.addListener(new AnimationListener());

        //将中间布局控件高度设置为撑满nsv
        View middleViewInNsv = v.findViewById(R.id.middleViewInNsv);
        ViewGroup.LayoutParams layoutParams = middleViewInNsv.getLayoutParams();
        layoutParams.height = Util.getScreenHeight(getActivity()) - Util.getStatusBarHeight(getActivity());

        //nsv自动滚动至
        nsv.post(new Runnable() {
            @Override
            public void run() {
                Log.w("MXY", "run");
                nsv.scrollTo(0, topViewInNsv.getLayoutParams().height);
            }
        });
    }

    /**
     * nsv触摸监听
     */
    private class NsvTouchListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    checkRefreshState();
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    /**
     * 检查是否出发刷新效果
     */
    private void checkRefreshState() {

        if (nsv.getScrollY() <= topViewInNsv.getLayoutParams().height / 2) {
            nsv.post(new Runnable() {
                @Override
                public void run() {
                    //顶部控件被拖拽超过一半，出发刷新效果
                    nsv.smoothScrollTo(0, topViewInNsv.getLayoutParams().height / 2);
                }
            });
            if (!isRefresh) {
                isRefresh = true;
                //开始刷新效果
                EventBus.getDefault().post("refresh");
            }
        } else {//顶部控件没有被拖拽超过一半，回到默认效果，不触发刷新效果
            nsv.post(new Runnable() {
                @Override
                public void run() {
                    //顶部控件被拖拽超过一半，出发刷新效果
                    nsv.smoothScrollTo(0, topViewInNsv.getLayoutParams().height);
                }
            });
        }
    }

    /**
     * nsv滚动监听
     */
    private class NsvScrollChangeListener implements NestedScrollView.OnScrollChangeListener {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            refreshFlexibleLayout(scrollY);
        }
    }

    /**
     * 刷新header视图高度
     *
     * @param scrollY
     */
    private void refreshFlexibleLayout(int scrollY) {
        //topview被拖动出现在界面中
        if (scrollY < topViewInNsv.getLayoutParams().height) {
            nsv.setInterceptTouchEvent(true);
            flexibleLayout.getLayoutParams().height = topViewInNsv.getLayoutParams().height - scrollY;
            flexibleLayout.requestLayout();
            flexibleLayout.invalidate();
        } else {//topview被隐藏
            if (flexibleLayout.getLayoutParams().height > 0) {
                flexibleLayout.getLayoutParams().height = 0;
                flexibleLayout.requestLayout();
                flexibleLayout.invalidate();
            }
            nsv.setInterceptTouchEvent(false);
        }
    }

    private class AnimationListener extends AnimatorListenerAdapter {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            nsv.smoothScrollTo(0, topViewInNsv.getLayoutParams().height);
            isRefresh = false;
        }
    }

    /**
     * 响应方法必须带参 Object子类
     * 响应时根据发布者对象类型进行响应
     */
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void handlerMessage(String str) {
        if ("refresh".equals(str)) {
            objectAnimator.start();
        }
        //受到粘性消息后进行处理，然后清除内存中粘性消息，节省资源
        EventBus.getDefault().removeAllStickyEvents();
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.w("MXY", "onStart");
        EventBus.getDefault().register(this);
    }


    @Override
    public void onStop() {
        super.onStop();
        Log.w("MXY", "onStop");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.w("MXY", "onResume");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.w("MXY", "onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.w("MXY", "onDetach");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.w("MXY", "onPause");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w("MXY", "onDestroy");
    }
}